<template>
  <div class="menu-tab-div-body">
    <!-- <div style="border:1px solid green;height:100px;margin:20px 50px;"> -->
    <div>
      <div class="text-left mb-3">
        <template>
          <el-input
            v-model="listQuery.emailAddress"
            :size="size"
            :placeholder="$t('common.enter', [$t('common.email')])"
            class="filter-item filter-left !w-40 mr-2"
            clearable
          />
          <el-select
            v-model="listQuery.groupId"
            class="filter-item filter-left !w-35"
            :placeholder="$t('common.select', [$t('common.grouping')])"
            filterable
            clearable
            :size="size"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button
            :size="size"
            class="filter-item filter-left"
            icon="el-icon-search"
            type="primary"
            style="margin-left: 5px"
            plain
            @click="refresh"
          >
            {{ $t('common.search') }}
          </el-button>
          <el-dropdown
            split-button
            class="ml-1"
            :size="size"
            type="success"
            @click="handleChangeGroup('selection')"
            @command="(cmd) => handleChangeGroup(cmd)"
          >
            {{ $t('email.batchGroup') }}(选中)
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="all">全部</el-dropdown-item>
              <el-dropdown-item command="currentPage">本页</el-dropdown-item>
              <el-dropdown-item command="success"
                >验证成功账号</el-dropdown-item
              >
              <el-dropdown-item command="failed">验证失败账号</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown
            split-button
            class="ml-1"
            :size="size"
            type="danger"
            plain
            @click="handleBatchDelete('selection')"
            @command="(cmd) => handleBatchDelete(cmd)"
          >
            {{ $t('email.batchDelete') }}(选中)
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="all">全部</el-dropdown-item>
              <el-dropdown-item command="currentPage">本页</el-dropdown-item>
              <el-dropdown-item command="success"
                >验证成功账号</el-dropdown-item
              >
              <el-dropdown-item command="failed">验证失败账号</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            class="!ml-1"
            :size="size"
            type="success"
            @click="handleShowAddEmailAccount(true)"
            >{{ $t('email.addEmailAccount') }}</el-button
          >
          <el-dropdown
            split-button
            class="ml-1"
            :size="size"
            type="primary"
            @click="handleValidateEmail('unknown')"
            @command="(cmd) => handleValidateEmail(cmd)"
          >
            验证(未验证账号)
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="all">全部</el-dropdown-item>
              <el-dropdown-item command="currentPage">本页</el-dropdown-item>
              <el-dropdown-item command="success"
                >验证成功账号</el-dropdown-item
              >
              <el-dropdown-item command="failed">验证失败账号</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            class="!ml-1"
            :size="size"
            type="success"
            @click="handleManageGroup()"
            >{{ $t('email.groupManagement') }}</el-button
          >
          <upload-excel
            class="inline-block"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          />

          <el-button
            :size="size"
            class="filter-item right filter-left filter-refresh"
            icon="el-icon-refresh"
            type="primary"
            plain
            @click="refresh"
          />
        </template>
      </div>
      <el-table
        ref="table"
        :data="currentPageEmailConfigs"
        v-loading="listLoading"
        height="calc(100vh - 310px)"
        row-key="id"
        @selection-change="handleSelection"
        border
      >
        <el-table-column
          align="center"
          type="selection"
          reserve-selection
          width="55"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="emailAddress"
          :label="$t('email.emailAccount')"
          min-width="180"
        >
        </el-table-column>
        <el-table-column align="center" prop="name" label="显示名称">
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('common.grouping')"
          width="100px"
        >
          <template slot-scope="scope">
            {{
              scope.row.emailConfigGroup ? scope.row.emailConfigGroup.name : ''
            }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="host" label="smtp服务器">
        </el-table-column>
        <el-table-column align="center" prop="state" label="状态" width="80px">
          <template slot-scope="{ row }">
            <span v-if="row.state === 'UNVERIFIED'" class="text-gray-500"
              >未验证</span
            >
            <span v-else-if="row.state === 'VERIFYING' || row.isVerifying"
              >验证中</span
            >
            <span v-else-if="row.state === 'SUCCESS'" class="text-green-500"
              >验证通过</span
            >
            <span v-else-if="row.state === 'FAILED'" class="text-red-500"
              >验证失败</span
            >
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="当日(发送数量/最大发送数量)"
          width="150px"
        >
          <template slot-scope="{ row }">
            <span
              >{{ row.lastDaySendNum }} /
              {{ row.maxLastDaySendNum || '无限制' }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="latestSendTime"
          label="最后一次发送时间"
          width="150px"
        >
          <template slot-scope="{ row }">
            <span v-if="row.latestSendTime" v-time="row.latestSendTime"></span>
            <span v-else class="text-gray-400">暂无</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="createdAt"
          :label="$t('common.createTime')"
          width="150px"
        >
          <template slot-scope="{ row }">
            <span v-time="row.createdAt"></span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('common.actions')"
          width="180px"
        >
          <template slot-scope="scope">
            <!-- <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button> -->
            <el-button type="text" size="small" @click="edit(scope.row)">{{
              $t('common.edit')
            }}</el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.isVerifying"
              @click="verifySmtp(scope.row)"
              >{{
                scope.row.isVerifying ? '验证中' : $t('email.revalidate')
              }}</el-button
            >
            <el-button
              type="text"
              size="small"
              class="!text-red-400"
              @click="deleteRow(scope.row)"
              >{{ $t('common.delete') }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="h-12.5 text-left">
        <change-group
          :show.sync="showChangeGroupVisible"
          @closeAction="refresh"
          :id="changeGroupIds"
        />
        <pagination
          v-show="emailConfigs.length > 0"
          :total="emailConfigs.length"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          :page-sizes="[10, 20, 30, 50, 100, 200]"
        />
      </div>
    </div>
    <manage-group :show.sync="showManageGroupVisible" />
    <add-sender-account
      :show.sync="showAddEmailAccountVisible"
      @closeAction="handlerSenderAccountAdded"
    />
    <edit-account
      :show.sync="showEditAccount"
      :id="id"
      @closeAction="refresh"
    />
  </div>
</template>

<script>
import { getAction, postAction } from '@/api/common'
import ManageGroup from '../manageGroup.vue'
import ChangeGroup from '../changeGroup.vue'
import UploadExcel from '@/components/UploadExcel/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import AddSenderAccount from './addSenderAccount.vue'
import EditAccount from '@/views/email/emailSendFree/editAccount'
import gql from 'graphql-tag'
import { EmailModule } from '@/store/modules/email'
export default {
  name: 'senderAccount',
  components: {
    UploadExcel,
    ManageGroup,
    ChangeGroup,
    Pagination,
    AddSenderAccount,
    EditAccount,
  },
  props: {
    addresser: {
      type: Array,
      default: () => [],
    },
    addresserLabel: {
      type: Array,
      default: () => [],
    },
  },
  apollo: {
    emailConfigs: {
      query: gql`
        query GetEmailConfigs($where: EmailConfigFilterInput) {
          emailConfigs: emailConfigsList(where: $where) {
            id
            emailAddress
            name
            host
            port
            ssl
            secret
            state
            emailConfigGroup {
              name
            }
            lastDaySendNum
            latestSendTime
            maxLastDaySendNum
            createdAt
          }
        }
      `,
      variables() {
        let where = {}
        if (this.listQuery.emailAddress) {
          where = {
            or: [
              {
                emailAddress: {
                  startsWith: this.listQuery.emailAddress,
                },
              },
              {
                emailAddress: {
                  endsWith: this.listQuery.emailAddress,
                },
              },
            ],
          }
        }
        if (this.listQuery.groupId) {
          where.emailConfigGroupId = {
            eq: this.listQuery.groupId,
          }
        }
        return {
          where,
        }
      },
      update: (data) => data.emailConfigs.map((m) => ({ ...m })),
      result({ data }) {
        const checkedSenders = EmailModule.context.state.checkedSenders
        if (this.selection.length === 0 && checkedSenders.length > 0) {
          for (let item of data.emailConfigs) {
            if (checkedSenders.includes(item.id)) {
              this.$refs.table.toggleRowSelection(item, true)
            }
          }
        }
      },
    },
    options: {
      query: gql`
        query GetEmailConfigGroupList {
          options: emailConfigGroupList {
            value: id
            label: name
          }
        }
      `,
    },
  },
  data() {
    return {
      size: 'mini',
      id: 0,
      emailConfigs: [],
      options: [],
      listQuery: {
        page: 1,
        limit: 100,
        emailAddress: '',
        groupId: '',
      },
      selection: [],
      showChangeGroupVisible: false,
      changeGroupIds: [],
      /// //////////////////////////发送账号//////////////////////////////////
      showManageGroupVisible: false,
      showAddEmailAccountVisible: false,
      showEditAccount: false,
      form: {
        Addresser: this.addresser,
        AddresserLabel: this.addresserLabel,
      },
      searchAddresser: '',
    }
  },
  created() {
    this.init()
    VUE.$on('EmailSendTaskStepCompleted', () => {
      this.refresh()
    })
  },
  beforeDestroy() {
    VUE.$off('EmailSendTaskStepCompleted')
  },
  inject: ['showProgressDialog'],
  computed: {
    listLoading() {
      return (
        this.$apollo.queries.options?.loading ||
        this.$apollo.queries.emailConfigs?.loading
      )
    },
    currentPageEmailConfigs() {
      let start = (this.listQuery.page - 1) * this.listQuery.limit
      let end = start + this.listQuery.limit
      return this.emailConfigs.slice(start, end)
    },
  },
  methods: {
    init() {},

    edit(row) {
      this.showEditAccount = true
      this.id = row.id
    },
    refresh() {
      const waitRefreshDone = (query) => {
        if (query.loading) {
          return new Promise((resolve) => {
            setTimeout(() => {
              resolve(waitRefreshDone(query))
            }, 100)
          })
        } else {
          return Promise.resolve()
        }
      }
      this.$apollo.queries.options?.refresh()
      this.$apollo.queries.emailConfigs?.refresh()

      return Promise.all([
        waitRefreshDone(this.$apollo.queries.options),
        waitRefreshDone(this.$apollo.queries.emailConfigs),
      ])
    },
    handleManageGroup() {
      this.showManageGroupVisible = true
    },
    handleShowAddEmailAccount() {
      this.showAddEmailAccountVisible = true
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message.warning(this.$t('email.maxUploadSize1M'))
      return false
    },

    handleSuccess({ results, header }) {
      const mapBoolean = (value) => {
        return isNaN(value)
          ? value === '是' ||
              value.toUpperCase() === 'TRUE' ||
              value.toUpperCase() === 'YES'
          : value == 1
      }
      const data = results.map((r) => ({
        emailAddress: r['邮箱地址'],
        emailType: this.getEmailType(r['邮箱地址']),
        secret: r['密码/客户端授权码'],
        driver: 'SMTP',
        host: r['smtp服务器'],
        port: r['端口'],
        ssl: mapBoolean(r['是否使用SSL']),
      }))
      postAction(data, 'EmailConfig/BatchConfigAddressee').then((res) => {
        if (res.code === 20000) {
          this.$message({
            message:
              res.message ?? this.$t('email.emailAuthoritionSuccessfully'),
            type: 'success',
          })
          this.refresh()
        } else {
          this.$message({
            message: res.message ?? this.$t('email.emailAuthoritionFailed'),
            type: 'warning',
          })
        }
      })
    },
    getEmailType(email) {
      const types = {
        'qq.com': 1,
        '126.com': 2,
        '163.com': 3,
        'sina.com': 4,
        'sohu.com': 5,
        'gmail.com': 6,
        'live.com': 7,
      }
      return types[email.split('@')[1]] ?? 0
    },
    handleChangeGroup(cmd) {
      let rows = this.getFilterRows(cmd)
      if (rows.length <= 0) {
        this.$message({
          type: 'info',
          message: this.$t('email.checkEmailsNeedToBatchGroup'),
        })
        return false
      }
      const ids = rows.map((m) => m.id)
      this.changeGroupIds = ids
      this.showChangeGroupVisible = true
    },
    handleSelection(val) {
      this.selection = val
      EmailModule.SET_EMAIL_CHECKED_SENDERS(this.selection.map((s) => s.id))
      this.form.AddresserLabel = val?.map((m) => m.emailAddress) ?? []
      this.$emit('update:addresser', val)
      this.$emit('update:addresserLabel', this.form.AddresserLabel)
    },
    getFilterRows(cmd) {
      let emails = []
      if (cmd === 'unknown') {
        emails = this.emailConfigs.filter((m) => m.state === 'UNVERIFIED')
      } else if (cmd === 'all') {
        emails = this.emailConfigs
      } else if (cmd === 'currentPage') {
        emails = this.currentPageEmailConfigs
      } else if (cmd === 'success') {
        emails = this.emailConfigs.filter((m) => m.state === 'SUCCESS')
      } else if (cmd === 'failed') {
        emails = this.emailConfigs.filter((m) => m.state === 'FAILED')
      } else if (cmd === 'selection') {
        emails = this.selection
      }
      return emails
    },
    handleBatchDelete(cmd) {
      let rows = this.getFilterRows(cmd)
      if (rows.length <= 0) {
        this.$message(this.$t('customer.checkDataNeedToBatchDelete'))
        return false
      }
      const uploadItems = [
        {
          name: this.$t('email.senderAccount'),
          num: rows.length,
          action: this.batchDeleteFunc,
          data: rows,
        },
      ]
      const uploadColumns = [
        { label: this.$t('email.senderAccount'), key: 'emailAddress' },
      ]
      this.showProgressDialog(uploadItems, uploadColumns, this.refresh, {
        title: this.$t('common.batchDeleteCantReverse'),
      })
    },
    batchDeleteFunc({ item, message }) {
      this.deleteEmailConfig(item.id)
        .then((res) => {
          let it = this.selection.find((m) => m.id === item.id)
          this.$refs.table.toggleRowSelection(it, false)
          message.success('[' + item.emailAddress + '] 删除成功')
        })
        .catch((res) => {
          message.failed('[' + item.emailAddress + '] ' + res.message)
        })
    },
    deleteRow(row) {
      this.$confirm(this.$t('email.confirmDeleteEmail', [row.emailAddress]))
        .then(() => {
          this.deleteEmailConfig(row.id).then(() => {
            this.$message.success(this.$t('common.deleteSuccessfully'))
            this.refresh()
          })
        })
        .catch(() => {})
    },
    deleteEmailConfig(id) {
      return postAction({}, `EmailConfig/Delete/${id}`)
    },
    handleValidateEmail(type) {
      let emails = this.getFilterRows(type)

      if (emails.length === 0) return this.$message.warning('验证邮箱不能为空')

      const uploadItems = [
        {
          name: this.$t('email.senderAccount'),
          num: emails.length,
          action: this.batchValidateFunc,
          data: emails,
        },
      ]
      const uploadColumns = [
        { label: this.$t('email.senderAccount'), key: 'emailAddress' },
      ]
      this.showProgressDialog(uploadItems, uploadColumns, this.refresh, {
        title: '验证发送邮箱有效性',
      })
    },
    batchValidateFunc({ item, message }) {
      this.$common.ExeInvoke((f) => {
        let msg = f.VerifySmtp(
          item.host,
          item.port,
          item.ssl,
          item.emailAddress,
          item.secret
        )
        let url = ''
        if (!msg) {
          url = 'emailConfig/verificationSuccess/' + item.id
        } else {
          url = 'emailConfig/verificationFailed/' + item.id
        }
        postAction({}, url).then(() => {
          if (!msg) {
            message.success('[' + item.emailAddress + '] 验证有效')
          } else {
            message.failed('[' + item.emailAddress + '] 验证无效, ' + msg.Data)
          }
        })
      })
    },
    verifySmtp(row) {
      row.isVerifying = true
      this.emailConfigs = [...this.emailConfigs]
      setTimeout(() => {
        this.$common.ExeInvoke((f) => {
          let msg = f.VerifySmtp(
            row.host,
            row.port,
            row.ssl,
            row.emailAddress,
            row.secret
          )
          let url = ''
          if (!msg) {
            this.$message.success('验证通过')
            url = 'emailConfig/verificationSuccess/' + row.id
          } else {
            this.$message.warning(`验证失败: ${msg.Data}`)
            url = 'emailConfig/verificationFailed/' + row.id
          }
          postAction({}, url).then(() => {
            this.refresh()
          })
        })
      }, 500)
    },
    randomSelect() {
      this.$refs.table.clearSelection()
      for (let row of this.emailConfigs) {
        let checked = Math.random() > 0.5
        if (checked) this.$refs.table.toggleRowSelection(row, true)
      }
    },
    async handlerSenderAccountAdded(email) {
      await this.refresh()

      const row = this.emailConfigs.find((m) => m.emailAddress === email)
      if (row) this.$refs.table.toggleRowSelection(row)
    },
  },
}
</script>

<style scoped></style>
